<template>
  <el-main class="app">
    <!-- 上面的面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item
          v-for="item in foldersList"
          :key="item.nodeId"
          @click.native="touch(item)"
          style="font-size:16px;"
          >{{ item.name }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <!-- 下方表格栏目 -->
    <div class="tableClass">
      <!-- 文件夹目录表格 -->
      <el-table
        style="folderTable"
        :data="tableFolderList"
        stripe
        :header-cell-style="{
          background: '#94AFCC',
          color: '#1A1C1E',
          padding: '0',
        }"
        :header-row-style="{ height: '35px' }"
        :row-style="{ height: '25px' }"
        :cell-style="{ padding: '0px' }"
        @row-dblclick="dbSelected"
      >
        <!-- 表头 -->
        <el-table-column label="名称" fit>
          <template slot-scope="scope">
            <i class="el-icon-folder"></i>
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <!-- 对该列的操作 -->
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <!-- 点击事件传参为scope.row.* -->
            <el-button
              @click.native.prevent="
                deleteFolder(scope.$index, tableFolderList)
              "
              type="text"
              >删除文件夹</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 文件表格 -->
      <el-table
        class="fileTable"
        :data="tableFileList"
        stripe
        :header-cell-style="{
          background: '#94AFCC',
          color: '#1A1C1E',
          padding: '0',
        }"
        :header-row-style="{ height: '35px' }"
        :row-style="{ height: '25px' }"
        :cell-style="{ padding: '0px' }"
      >
        <!-- 表头 -->
        <el-table-column label="名称" fit>
          <template slot-scope="scope">
            <i class="el-icon-document"></i>
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="format" label="资源格式" fit />
        <el-table-column prop="size" label="大小" fit />
        <el-table-column prop="uploadDate" label="上传时间" fit />
        <!-- 对该列的操作 -->
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <!-- 点击事件传参为scope.row.* -->
            <a :href="scope.row.link" type="text" class="downLoad">下载</a>
            <el-button
              style="margin-left:15px"
              @click.native.prevent="deleteFile(scope.$index, tableFileList)"
              type="text"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top:35px;float: left; width:100%">
      <el-button class="btn" @click="newFolder" style="display:inline"
        >新建文件夹</el-button
      >
      <el-upload
        action
        :before-upload="beforeAvatarUpload"
        :http-request="upLoad"
        :show-file-list="false"
        style="display:inline; margin-left:25px"
      >
        <el-button class="btn">上传文件</el-button>
      </el-upload>
      <!--  -->
    </div>
    <div style="width:100%; margin-top:100px" v-if="submiting">
      <div>文件上传进度</div>
      <el-progress :percentage="progress"></el-progress>
    </div>
  </el-main>
</template>

<script>
import COS from "cos-js-sdk-v5";
import $ from "jquery";

export default {
  data() {
    return {
      foldersList: [
        {
          // 第一级目录是课程资源目录，但是不用显示出来，通过nodeId=0来获取后面内容
          nodeId: 0,
          isFolder: true,
          name: "课程资源",
          format: null,
          size: null,
          link: null,
          uploadDate: null,
        },
      ],
      tableFolderList: [],
      tableFileList: [],

      // 当前所在目录
      currentFolder: {
        nodeId: 0,
        isFolder: "",
        name: "",
        format: "",
        size: "",
        link: "",
        uploadDate: "",
      },

      // 新建文件夹
      newFolderName: "",
      uploadFile: "",
      // 上传文件资源
      uploadFileData: {
        nodeId: "",
        resourceNode: {
          isFolder: "",
          key: "",
          name: "",
          format: "",
          size: "",
          link: "",
        },
      },

      // 上传进度
      progress: 0,
      // 是否正在上传
      submiting: false,

      // 唯一标识某一节课
      identifier: 1,

      // 标识当前文件夹路径（面包屑上的路径）
      route: "",

      // 标识删除文件夹的前缀
      deleteFolderPrefix: "",

      // 删除文件夹的内容
      deleteFolderContent: [],
    };
  },
  methods: {
    //获得文件列表,后刷新
    returnFileList(nodeId) {
      let options = {};
      options.sections = this.$store.state.temp_courseSections;
      options.nodeId = nodeId;
      this.$http
        .post(this.$api.CourseResourceGetFileListOfNextLevel, options)
        .then((resp) => {
          if (resp.success) {
            console.log(resp.data);
            this.handleOriginalFileList(resp.data);
          } else {
            this.$handleFailResp(this, resp);
          }
        });
    },

    // 获取当前文件夹路径，用于存储文件
    storeFileRoute() {
      for (var j = 0; j < this.foldersList.length; j++) {
        if (j == this.foldersList.length - 1) {
          this.route = this.route + this.foldersList[j].name + "/";
        } else {
          this.route = "/" + this.route + this.foldersList[j].name + "/";
        }
      }
      console.log("route");
      console.log(this.route);
    },

    //上传文件资源、创建文件夹  如果是文件夹，resourceNode可以不传  后刷新
    CreateResourceNode(nodeId, resourceNode) {
      let options = {};
      options.sections = this.$store.state.temp_courseSections;
      options.nodeId = nodeId;
      options.resourceNode = resourceNode;

      this.$http
        .post(this.$api.CourseResourceCreateResourceNode, options)
        .then((resp) => {
          if (resp.success) {
            console.log(resp.data);
            this.returnFileList(this.currentFolder.nodeId);
          } else {
            this.$handleFailResp(this, resp);
          }
        });
    },

    // 刷新文件夹列表、文件列表
    handleOriginalFileList(OriginalFileList) {
      //清空
      this.tableFolderList = [];
      this.tableFileList = [];
      for (let index in OriginalFileList) {
        if (OriginalFileList[index].isFolder) {
          // 是文件夹
          this.tableFolderList.push(OriginalFileList[index]);
        } else {
          this.tableFileList.push(OriginalFileList[index]);
        }
      }
    },

    // 点击面包屑中的一个item
    touch(item) {
      console.log("item:");
      console.log(item);
      while (this.foldersList.pop() != item) {}
      this.foldersList.push(item);
      console.log("foderList:");
      console.log(this.foldersList);
      // 更新currentFolder
      this.resetCurrentFolder(item);
    },

    // 在文件夹表格里点击一个文件夹
    dbSelected(item) {
      console.log("dbclick");
      this.resetCurrentFolder(item);
      // 更新面包屑
      this.foldersList.push(item);
    },

    // 更新当前目录
    resetCurrentFolder(item) {
      this.currentFolder = item;
      this.returnFileList(item.nodeId);
    },

    //删除资源接口
    DeleteResourceNode(nodeId) {
      let options = {};
      options.sections = this.$store.state.temp_courseSections;
      options.nodeId = nodeId;
      var _this = this;
      this.$http
        .post(this.$api.CourseResourceDeleteResourceNode, options)
        .then((resp) => {
          if (resp.success) {
            this.$myMessage.success(this, "删除成功！");
            setTimeout(
              setTimeout(function() {
                _this.$router.go(0);
              }, 600)
            );
          } else {
            this.$handleFailResp(this, resp);
          }
        });
    },

    // 删除文件夹
    deleteFolder(index, rows) {
      var that = this;
      console.log(index);
      console.log(rows[index]);
      this.route = "";
      this.storeFileRoute();
      this.deleteFolderPrefix =
        this.identifier + "/" + this.route + rows[index].name;
      console.log("this.deleteFolderPrefix");
      console.log(this.deleteFolderPrefix);
      this.returnList();
      this.$confirm("此操作将永久删除该文件夹, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 这个就是被删除文件夹的nodeId
          var nodeId = rows[index].nodeId;
          console.log(nodeId);
          // 这里需要连接接口，详细见接口文档“删除资源”
          that.DeleteResourceNode(nodeId);
          // 删除表格中的这一行
          // rows.splice(index, 1);

          var cos = that.getCOS();
          cos.deleteMultipleObject(
            {
              Bucket: "mybucket-1304114494",
              Region: "ap-guangzhou" /* 必须 */,
              Objects: that.deleteFolderContent,
            },
            function(err, data) {
              console.log(err || data);
              that.returnList();
            }
          );
          // this.$message({
          //   type: "success",
          //   message: "删除成功!",
          // });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 删除文件
    deleteFile(index, rows) {
      console.log(index);
      console.log(rows[index]);
      var that = this;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 这个就是被删除文件夹的nodeId,key等信息
          var nodeId = rows[index].nodeId;
          var key = rows[index].key;
          console.log(nodeId);
          console.log(key);
          // 这里要重新表格数据
          // 这里需要连接接口，详细见接口文档“删除资源”
          that.DeleteResourceNode(nodeId);
          // 删除表格中的这一行
          // rows.splice(index, 1);
          console.log(this.tableFileList);

          var cos = that.getCOS();
          cos.deleteObject(
            {
              Bucket: "mybucket-1304114494",
              Region: "ap-guangzhou" /* 必须 */,
              // 保存文件时的key，这里要进行替换
              Key: key,
            },
            function(err, data) {
              if (err) {
                that.$message.error("课程资源删除失败");
              } else {
                // 提示上传成功
                // that.$message({
                //   message: "课程资源删除成功",
                //   type: "success",
                // });
                // 接接口，详细见接口文档“删除资源”
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 返回该文件夹中的所有文件
    returnList() {
      var that = this;
      var cos = this.getCOS();
      cos.getBucket(
        {
          Bucket: "mybucket-1304114494",
          Region: "ap-guangzhou",
          // 路径, 返回数组的第一个元素为文件夹
          Prefix: that.deleteFolderPrefix,
        },
        function(err, data) {
          // 打印返回数据中的内容
          console.log(err || data.Contents);
          for (var i = 0; i < data.Contents.length; i++) {
            that.deleteFolderContent.push({ Key: data.Contents[i].Key });
          }
          console.log("deleteFolderContent:");
          console.log(that.deleteFolderContent);
        }
      );
    },

    // 新建文件夹
    newFolder() {
      var that = this;
      // 提醒输入创建文件夹名称
      this.$prompt("请输入文件夹名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^\S+$/,
        inputErrorMessage: "文件夹名称不能为空以及包含空格",
      })
        .then(({ value }) => {
          // 文件名称
          that.newFolderName = value;
          // 这里要向后端发送信息，详细见接口文档“上传文件资源/创建文件夹”

          let resourceNode = {
            isFolder: true,
            key: null,
            name: value,
            format: null,
            size: null,
            link: null,
          };
          // 接口中的nodeId在currentFolder中取出
          this.CreateResourceNode(this.currentFolder.nodeId, resourceNode);

          // this.$message({
          //   type: "success",
          //   message: "新建文件夹成功",
          // });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消创建文件夹",
          });
        });
    },

    // 提交前获取文件的相关信息
    beforeAvatarUpload(file) {
      // console.log("file");
      // console.log(file);
      this.uploadFile = file;
      this.uploadFileData.resourceNode.name = file.name.substring(
        0,
        file.name.lastIndexOf(".")
      );
      this.uploadFileData.resourceNode.format = file.name.substring(
        file.name.lastIndexOf(".") + 1,
        file.name.length
      );
      // console.log(this.uploadFileData.resourceNode.name);
      // console.log(this.uploadFileData.resourceNode.format);
      // 上传文件大小
      if (file.size < 1024) {
        this.uploadFileData.resourceNode.size = file.size.toFixed(2) + " B";
      } else if (file.size < 1024 * 1024) {
        this.uploadFileData.resourceNode.size =
          (file.size / 1024).toFixed(2) + " kB";
      } else if (file.size < 1024 * 1024 * 1024) {
        this.uploadFileData.resourceNode.size =
          (file.size / 1024 / 1024).toFixed(2) + " MB";
      } else if (file.size < 1024 * 1024 * 1024 * 1024) {
        this.uploadFileData.resourceNode.size =
          (file.size / 1024 / 1024 / 1024).toFixed(2) + " GB";
      }
      console.log(this.uploadFileData.resourceNode.size);
      this.uploadFileData.resourceNode.isFolder = false;
    },

    // 重置状态
    resetUploadFileData() {
      console.log("重置ing");
      this.submiting = false;
      this.uploadFileData.nodeId = "";
      this.uploadFileData.resourceNode.isFolder = null;
      this.uploadFileData.resourceNode.key = null;
      this.uploadFileData.resourceNode.name = null;
      this.uploadFileData.resourceNode.format = null;
      this.uploadFileData.resourceNode.size = null;
      this.uploadFileData.resourceNode.link = null;
    },

    // 上传文件
    upLoad() {
      this.route = "";
      this.storeFileRoute();
      console.log("点击了上传文件按钮");
      var that = this;
      // 弹出提示框询问是否确认提交
      this.$confirm("确认上传资源？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 身份认证
          var cos = this.getCOS();
          that.submiting = true;
          cos.putObject(
            {
              Bucket: "mybucket-1304114494",
              Region: "ap-guangzhou",
              // 唯一标识文件的key：前面为文件夹，后面为文件名
              Key: that.identifier + that.route + that.uploadFile.name,
              StorageClass: "STANDARD",
              Body: that.uploadFile, // 上传文件对象
              // 进度回调函数
              onProgress: function(progressData) {
                console.log(progressData.percent);
                // 更新显示进度条
                that.progress = progressData.percent * 100;

                // progressData.total 整个文件的大小
                // progressData.loaded 已上传文件内容大小， progressData.speed 上传文件速度， progressData.percent 上传文件百分百
                //console.log(progressData.total);
              },
            },
            function(err, data) {
              // 这里是打印文件的保存路径
              console.log(data);
              if (err) {
                that.$message.error("课程资源上传失败");
              } else {
                // 提示上传成功
                that.$message({
                  message: "课程资源上传成功",
                  type: "success",
                });

                // 向后端发请求
                // 记录信息, 参见接口文档“上传文件资源/创建文件夹”
                // link
                var url = "https://";
                var address = data.Location;
                that.uploadFileData.resourceNode.link = url + address;
                // 清空route
                that.route = "";
                // key
                that.uploadFileData.resourceNode.key =
                  that.identifier + that.route + that.uploadFile.name;
                console.log("that.uploadFileData.resourceNode.key");
                console.log(that.uploadFileData.resourceNode.key);
                console.log("上传完资源了");
                console.log(that.uploadFileData.resourceNode);
                that.CreateResourceNode(
                  that.currentFolder.nodeId,
                  that.uploadFileData.resourceNode
                );
                // 连完接口之后要重置文件信息
                that.resetUploadFileData();
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消课程资源上传",
          });
        });
    },

    // 身份认证
    getCOS() {
      var cos = new COS({
        AppId: "1304114494",
        SecretId: "AKIDwhU5nHLegU7C5rloQmslkVZOyRgrElU4",
        SecretKey: "d5SdcLMI7IKHzUxDEIAbstnTfIvsa3HJ",
      });
      return cos;
    },
  },

  mounted() {
    // 在mounted的时候就要调用接口，刷新第一级页面
    this.returnFileList(this.currentFolder.nodeId);
    this.identifier = this.$store.state.identifier
    // 详细见接口文档“获得下一级文件列表”，第一级页面nodeId为0调用
  },
};
</script>

<style lang="less" scope>
.app {
  margin: 0 auto;
  vertical-align: middle;
  width: 90%;
  padding: 20px;
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  border: 3px solid rgba(0, 0, 0, 0.04);
}

.breadcrumb {
  margin: 15px;
}

.el-breadcrumb__item:last-child .el-breadcrumb__inner,
.el-breadcrumb__item:last-child .el-breadcrumb__inner a,
.el-breadcrumb__item:last-child .el-breadcrumb__inner a:hover,
.el-breadcrumb__item:last-child .el-breadcrumb__inner:hover {
  color: #333333;
  font-size: 17px;
  font-weight: 500;
}

.fileTable {
  margin-top: 20px;
}

.downLoad {
  text-decoration: none;
  color: #409eff;
}

.btn {
  background: rgb(89, 136, 179);
  color: #f2f2f2;
  font-weight: 500;
  font-size: 16px;
}
</style>
